package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomerException;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.pojo.SetmealDish;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    SetmealDishService setmealDishService;

    @Autowired
    SetmealMapper setmealMapper;

    //保存套餐数据，以及套餐菜品的相关数据
    @Override
    public void savaWithDish(SetmealDto setmealDto) {
        //1.添加套餐数据，操作setmeal表，添加一条数据
        this.save(setmealDto);//保存之前id没有数据，保存之后id才有数据

        //2.添加套餐和菜品的关联数据，操作setmeal_dish表，添加多条数据
        //TODO 给每个套餐菜品(SetmealDish)添加套餐id
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> setmealDish.setSetmealId(setmealDto.getId()));
        setmealDishService.saveBatch(setmealDishes);
    }

    //分页查询
    @Override
    public Page<SetmealDto> pageSetmealDto(Long page, Long pageSize, String name) {
        //查两张表（dish,category），还得分页
        //左外查询select * from dish  left (outer) join category on

        //创建分页对象
        Page<SetmealDto> pageInfo = new Page<>(page, pageSize);
        //调用mapper
        return setmealMapper.pageSetmealDto(pageInfo,name);
    }

    @Override
    public void deleteByIds(Long[] ids) {

        //要求1：套餐正在售卖不可删除 select count(*) fromsetmeal where id in (ids) and status=1
        Integer count = this.lambdaQuery()
            .in(Setmeal::getId, ids)
            .eq(Setmeal::getStatus, 1)
            .count();
        if(count > 0){
            throw new CustomerException("有套餐正在售卖，不可删除，请先停售该套餐");
        }
        //要求2：删除套餐的同时（setmeal)还要删除关联的数据(setmeal_dish)
        //delete from setmeal where id in (ids)
        this.removeByIds(Arrays.asList(ids));
        //delete from setmeal_dish where setmeal_ id in (ids)
        setmealDishService.lambdaUpdate()
            .in(SetmealDish::getSetmealId,ids)
            .remove();

    }
}
